package com.a21vianet.quincysx.demo.socket;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class RemoteService extends Service {
    private static final String TAG = RemoteService.class.getSimpleName();

    private boolean mIsServiceDestoryed = false;


    @Override
    public void onCreate() {
        new Thread(new TcpService()).start();
        super.onCreate();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "销毁服务");
        mIsServiceDestoryed = true;
        super.onDestroy();
    }

    private class TcpService implements Runnable {

        @Override
        public void run() {
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(8895);
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
            while (!mIsServiceDestoryed) {
                try {
                    final Socket client = serverSocket.accept();
                    Log.e(TAG, "等待连接");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                responseClient(client);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void responseClient(Socket client) throws IOException {
        Log.e(TAG, "有客户端连接");
        BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(client.getOutputStream()),
                true);

        while (!mIsServiceDestoryed) {
            Log.e(TAG, "等待消息中");
            String msg = reader.readLine();
            Log.e(TAG, "收到消息:" + msg);
            if (msg == null) {
                break;
            }
            String responseMsg = "你好我是 Service 端";
            writer.println(responseMsg);

            Log.e(TAG, "发送消息:" + responseMsg);
        }

        Log.e(TAG, "关闭连接");
        reader.close();
        writer.close();
        client.close();
    }
}
